package com.example.librarymanagementsystembackend.utils;


import org.apache.tika.Tika;
import org.apache.tika.mime.MimeType;
import org.apache.tika.mime.MimeTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
public class FileUtils {

    @Value("${resource-dir}")
    private String resourceDir;

    /**
     * @param path 文件目标目录的路径
     */
    public Resource getFile(String path) {
        try {
            // 构建文件路径
            Path filePath = Paths.get(this.resourceDir, path);
            return new FileSystemResource(filePath.toFile());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param path 文件目标目录的路径
     * @return 文件存储的相对路径
     */
    public String addFile(String path, MultipartFile file) {
        if (file == null) {
            throw new InvalidRequestException("上传失败，文件上传方式有误");
        }
        if (file.isEmpty()) {
            throw new InvalidRequestException("上传失败，文件为空");
        }

        try {
            // 创建目标目录
            Path targetDir = Paths.get(this.resourceDir, path);
            if (!Files.exists(targetDir)) {
                Files.createDirectories(targetDir);
            }

            // 保存文件
            String extension = this.getExtensionFromContent(file.getBytes());
            String filename = this.generateUniqueFilename() + extension;
            Path targetPath = targetDir.resolve(filename);
            file.transferTo(targetPath);

            return Paths.get(path, filename).normalize().toString().replace("\\", "/");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String generateUniqueFilename() {
        return
                DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").format(LocalDateTime.now())
                + "-"
                + UUID.randomUUID().toString().replace("-", "");
    }

    public String getExtensionFromContent(byte[] fileData) throws Exception {
        // 1. 检测MIME类型
        Tika tika = new Tika();
        String mimeType = tika.detect(fileData);

        // 2. 将MIME类型转换为扩展名
        MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
        MimeType type = allTypes.forName(mimeType);
        return type.getExtension(); // 返回如".png"
    }
}
